package top.hekun.study;

import org.htmlunit.BrowserVersion;
import org.htmlunit.WebClient;
import org.htmlunit.html.HtmlPage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;

/**
 * 无法渲染echarts图形 只能渲染一般页面
 */
public class Main {
    private static String pathname = "C:\\kk\\sakura\\study-record\\reptlie-heml-unit\\src\\main\\java\\top\\hekun\\study";

    public static void main(String[] args) {
        System.out.println("Hello world!");
        // 实例化客户端 自动关闭释放内存 模拟谷歌浏览器
        try (WebClient webClient = new WebClient(BrowserVersion.CHROME)) {
            //忽略js错误
            webClient.getOptions().setThrowExceptionOnScriptError(false);
            //超时时间
//            webClient.getOptions().setTimeout(30_000);
            //开始请求网站
//            String fileNanme = "EchartsLineTest.html";
            String fileNanme = "AntvG2LineTest.html";

            HtmlPage page = webClient.getPage(new File(new File(pathname), fileNanme).toURI().toURL());


//            System.out.println(page.asXml());
            // 触发按钮
//            Page downloadButton = page.getElementById("cyberDownloadButton").click();
//            Page enclosedPage = downloadButton.getEnclosingWindow().getEnclosedPage();
//            System.out.println(enclosedPage.getUrl());
//            DomElement cyberDownloadImg = page.getElementById("divBase64");
//            String srcValue = cyberDownloadImg.asNormalizedText();
//            String base64value = srcValue.split(",")[1];
//            byte[] decodedData = Base64.getDecoder().decode(base64value);
//            InputStream contentAsStream = enclosedPage.getWebResponse().getContentAsStream();
////            String responseHeaderValue = enclosedPage.getWebResponse().getResponseHeaderValue(HttpHeader.CONTENT_DISPOSITION);
////            String documentName = responseHeaderValue.split(";")[1].split("=")[1].trim();
//            String documentName = "test.png";
//            documentName = URLDecoder.decode(documentName);
//            System.out.println("文件下载成功：{"+documentName+"}");
            //存入数据库
//            convert(decodedData);

            Thread.sleep(5000);


        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }

    public static void convert(byte[] decodedData) {
        try {
            FileOutputStream outputStream = new FileOutputStream(new File(new File(pathname), "out.png"));
            outputStream.write(decodedData);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}